from flask import Flask, render_template, jsonify, request
import pandas as pd

app = Flask(__name__)

# 读取并预处理数据
data = pd.read_csv('data/cleaned_combined_data.csv')
data['时间'] = pd.to_datetime(data['时间'], errors='coerce')  # 解析时间列
data['month'] = data['时间'].dt.month  # 提取月份用于分析
data['hour'] = data['时间'].dt.hour  # 提取小时用于分析

# 主页面路由
@app.route('/')
def index():
    return render_template('index.html')

# 数据摘要 API
@app.route('/api/data_summary')
def data_summary():
    # 地区分布统计
    region_distribution = data['地区'].value_counts().to_dict()

    # 热门博物馆统计
    top_museums = data['博物馆名称'].value_counts().head(10).to_dict()

    # 按小时访问分布
    hour_distribution = data['hour'].value_counts().sort_index().to_dict()

    # 按月访问分布
    monthly_distribution = data['month'].value_counts().sort_index().to_dict()

    # 数据摘要统计
    total_visits = len(data)  # 总访问量
    unique_users = data['用户名称'].nunique()  # 独立用户数量
    unique_museums = data['博物馆名称'].nunique()  # 独特博物馆数量

    return jsonify({
        "region_distribution": region_distribution,
        "top_museums": top_museums,
        "hour_distribution": hour_distribution,
        "monthly_distribution": monthly_distribution,
        "summary_statistics": {
            "total_visits": total_visits,
            "unique_users": unique_users,
            "unique_museums": unique_museums
        }
    })

# 数据筛选 API
@app.route('/api/filter_data', methods=['GET'])
def filter_data():
    # 获取筛选参数
    region = request.args.get('region')  # 地区参数
    start_date = request.args.get('start_date')  # 开始日期
    end_date = request.args.get('end_date')  # 结束日期

    # 根据参数筛选数据
    filtered_data = data
    if region:
        filtered_data = filtered_data[filtered_data['地区'] == region]
    if start_date:
        filtered_data = filtered_data[filtered_data['时间'] >= pd.to_datetime(start_date)]
    if end_date:
        filtered_data = filtered_data[filtered_data['时间'] <= pd.to_datetime(end_date)]

    # 筛选后的数据统计
    region_distribution = filtered_data['地区'].value_counts().to_dict()
    top_museums = filtered_data['博物馆名称'].value_counts().head(10).to_dict()
    hour_distribution = filtered_data['hour'].value_counts().sort_index().to_dict()

    return jsonify({
        "region_distribution": region_distribution,
        "top_museums": top_museums,
        "hour_distribution": hour_distribution
    })

if __name__ == '__main__':
    app.run(debug=True)
